<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/7 0007
 * Time: 下午 5:38
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreAdminPost;
use App\Models\Admin;
use Illuminate\Http\Request;
use Silber\Bouncer\Database\Role;

class AdminController extends Controller
{
    /**
     * 后台管理
     */
    public function __construct()
    {
        view()->share('menu', 'admin');
    }

    public function index(Request $request)
    {
        //查询管理员列表
        $name = $request->get('name');
        $pageSize = 15;
        if (!empty($name)) {
            $list = Admin::with('roles')->whereRaw('username like ?', ['%'.$name.'%'])->paginate($pageSize);
            $url_data = compact('name');
        } else {
            $list = Admin::with('roles')->paginate($pageSize);
        }
        $page_num = $list->firstItem();

        return view('admin/admin/index', compact('list', 'page_num', 'url_data'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $list = Role::all();
        return view('admin/admin/create',compact('list'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreAdminPost $request)
    {
        //validate
        $request->validate([
            'username' => 'required|unique:admins',
            'password' => 'required|min:6|max:25'
        ]);
        //get param
        $username = $request->get('username');
        $password = $request->get('password');
        $roles = array_filter($request->input('role'));
        //check
        if (empty($username) || empty($password)) {
            return back()->with(['msg'=>'信息填写不全','status'=>0]);
        }
        if (empty($roles)){
            return back()->with(['msg'=>'未分配角色','status'=>0]);
        }
        //find in database
        $AdminModel = new Admin();
        $res = $AdminModel->where('username', $username)->first();
        if (!empty($res)) {
            return back()->with(['msg'=>'该管理员名称已存在','status'=>0]);
        }
        $AdminModel->username = $username;
        $AdminModel->password = md5($password);
        $AdminModel->save();
        foreach ( $roles as $role) {
            $AdminModel->assign($role);
        }
        return back()->with(['msg'=>'添加成功','status'=>1,'msg_url'=>'/admin/admin']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //find in database
        $data = (new Admin())->find($id);
        $list = Role::all();

        $roles = $data->roles;

        foreach ($roles as $item){
            $item = collect($item)->toArray();
            $role_ids[] = $item['pivot']['role_id'];
        }

        return view('admin/admin/edit', compact('list','data','role_ids'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $username = $request->get('username');
        $old_password = $request->get('old_password');
        $password = $request->get('password');
        $roles = array_filter($request->input('role'));

        //防止刷新造成重复提交
//        session()->forget('')csrf_token();
//        dd($request->all());
        //check
        if ((empty($old_password) && !empty($password)) || (!empty($old_password) && empty($password))) {
            return back()->with(['msg'=>'信息填写不全','status'=>0]);
        }
        if (empty($roles)){
            return back()->with(['msg'=>'未分配角色','status'=>0]);
        }
        //find in database
        $res = Admin::find($id);
        if ($res['username'] != $username) {
            return back()->with(['msg'=>'管理员名称不一致','status'=>0]);
        }
        if (Admin::where([['id','!=',$id],['username',$username]])->first()) {
            return back()->with(['msg'=>'管理员名称重复','status'=>0]);
        }
        if ($password && $old_password && $res['password'] != md5($old_password)) {
            return back()->with(['msg'=>'旧密码填写错误','status'=>0]);
        }
        //update
        $res->username = $username;
        if (!empty($password)){
            $res->password = md5($password);
        }
        $res->save();

        foreach ($res->roles as $role) {
            $res->retract($role);
        }
        foreach ( $roles as $role) {
            $res->assign($role);
        }
        return back()->with(['msg'=>'修改成功','status'=>1,'msg_url'=>'/admin/admin']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Admin::destroy($id);
        return ['status'=>1,'msg'=>'删除成功'];
    }
}
